package com.example.fresh_market.fragments;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.example.fresh_market.R;
import com.example.fresh_market.adapter.ProdCateAdapter;
import com.example.fresh_market.adapter.ProductAdapter;
import com.example.fresh_market.databinding.FragmentMainBinding;
import com.example.fresh_market.entity.ProdCate;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.request.PageResult;
import com.example.fresh_market.request.UsrProductPageResp;
import com.example.fresh_market.utils.HttpUtil;
import com.example.fresh_market.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import lombok.NoArgsConstructor;

@NoArgsConstructor
public class MainFragment extends Fragment {
    private final ProdCate defaultCate = new ProdCate(-1L, "全部", "", true, 0);
    private FragmentMainBinding binding;
    private TextView searchText;
    private TextView number;
    private Context mContext;
    private AlertDialog chooseDialog = null;
    private View view_choose;
    private ProdCateAdapter prodCateAdapter = null;
    private ProductAdapter prodAdapter = null;
    private LayoutInflater inflater;
    private RecyclerView prodList;
    private RecyclerView cateList;

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentMainBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        this.inflater = inflater;
        searchText = binding.searchEditText;
        ImageButton searchBtn = binding.searchButton;
        mContext = this.getContext();
        // 构建商品规格选择框
        initDialog();
        initCate();
        cateList = binding.recCate;
        prodList = binding.recProd;
        // 设置商品列表的数据
        prodList.setLayoutManager(new LinearLayoutManager(mContext));
        // 初始化适配器 和 事件监听器
        prodAdapter = new ProductAdapter(mContext, new ProductAdapter.MyClickListener() {
            @Override
            public void onChooseClick(View v, int position) {
                chooseDialog.show();
                if (view_choose != null) {
                    UsrProductPageResp product = prodAdapter.getItem(position);
                    TextView id = view_choose.findViewById(R.id.choose_productId);
                    id.setText(String.valueOf(product.getId()));
                    ImageView img = view_choose.findViewById(R.id.choose_productImage);
                    HttpUtil.loadImage(img, product.getImage(),
                            new RequestOptions().override(1080, 600));
                    TextView name = view_choose.findViewById(R.id.choose_productName);
                    name.setText(product.getName());
                    TextView intro = view_choose.findViewById(R.id.choose_productInfo);
                    intro.setText(product.getInfo());
                    number.setText("1");
                }
            }

            @Override
            public void onItemClick(View view, int position) {

            }
        });
        prodList.setAdapter(prodAdapter);

        // 设置商品类别的数据
        cateList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        prodCateAdapter = new ProdCateAdapter((cate, position) -> {
            String search = searchText.getText().toString().trim();
            initData(search, cate.getId() == -1 ? null : cate.getId());
        });
        cateList.setAdapter(prodCateAdapter);
        // 设置搜索按钮的点击事件
        searchBtn.setOnClickListener(v -> {
            // 得到当前选中的商品类别
            ProdCate cate = prodCateAdapter.getCurrentCate();
            // 获取搜索关键字
            String search = searchText.getText().toString().trim();
            initData(search, cate.getId() == -1 ? null : cate.getId());
        });
        // 初始化数据
        initCate();
        // 初始化商品列表
        initData(null, null);
        return view;
    }

    public void initCate() {
        String url = "/usr/index/product/cate?page=1&size=10000";
        HttpUtil.get(mContext, url, response -> {
            Gson gson = new Gson();
            ApiResponse<PageResult<ProdCate>> apiResponse = gson.fromJson(response,
                    new TypeToken<ApiResponse<PageResult<ProdCate>>>() {
                    }.getType());
            prodCateAdapter.submitList(new ArrayList<ProdCate>() {{
                add(defaultCate);
                addAll(apiResponse.getData().getList());
            }});
        });
    }

    public void initData(String keyword, Long cateId) {
        StringBuilder stringBuilder = new StringBuilder("/usr/index/product?page=1&size=10000");
        if (keyword != null) {
            stringBuilder.append("&keyword=").append(keyword);
        }
        if (cateId != null) {
            stringBuilder.append("&cateId=").append(cateId);
        }
        String url = stringBuilder.toString();
        HttpUtil.get(mContext, url, response -> {
            Gson gson = new Gson();
            ApiResponse<PageResult<UsrProductPageResp>> apiResponse = gson.fromJson(response,
                    new TypeToken<ApiResponse<PageResult<UsrProductPageResp>>>() {
                    }.getType());
            prodAdapter.submitList(apiResponse.getData().getList());
        });
    }

    public void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        view_choose = inflater.inflate(R.layout.dialogue_choose, null, false);
        number = view_choose.findViewById(R.id.choose_productNum);
        builder.setView(view_choose);
        chooseDialog = builder.create();
        view_choose.findViewById(R.id.button_exit).setOnClickListener(v -> chooseDialog.dismiss());
        view_choose.findViewById(R.id.button_buy).setOnClickListener(v -> {
            TextView id = view_choose.findViewById(R.id.choose_productId);
            Map<String, String> params = new HashMap<>();
            params.put("productId", id.getText().toString());
            params.put("productNum", number.getText().toString());
            HttpUtil.post(mContext, "/usr/cart", params, response -> {
                ApiResponse apiResponse = new Gson().fromJson(response, ApiResponse.class);
                if (apiResponse.getCode() == 200) {
                    ToastUtil.showToast(mContext, "加入购物车成功!");
                }
            });
            chooseDialog.dismiss();
        });

        view_choose.findViewById(R.id.button_subtract).setOnClickListener(v -> {
            int i = Integer.parseInt(String.valueOf(number.getText()));
            if (i > 1) {
                i--;
            }
            number.setText(String.valueOf(i));
        });

        view_choose.findViewById(R.id.button_add).setOnClickListener(v -> {
            int i = Integer.parseInt(String.valueOf(number.getText()));
            number.setText(String.valueOf(++i));
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
//            initCate();
//            initData(null, null);
        }
    }
}